using UnityEngine;
[ExecuteInEditMode]
public class HexagonMap : MonoBehaviour
{
    public float nodeScale;
    public GameObject prefab;
    public Material[] materials;
    public Vector2 mapSize;
    private void OnEnable()
    {
        for (var x = -mapSize.x; x < mapSize.x; x++)
            for (var y = -mapSize.y; y < mapSize.y; y++)
            {
                var node = GameObject.Instantiate(prefab);
                node.name = x + "," + y;
                node.transform.SetParent(transform);
                node.transform.localPosition = x * HexagonNode.width + y * HexagonNode.height;
                var delta = -(x - x % 2) * HexagonNode.height / 2;
                if (x < 0)
                    delta = -(x + x % 2) * HexagonNode.height / 2;
                node.transform.localPosition += delta;
                node.transform.localPosition = new Vector3(
                    node.transform.localPosition.x / transform.lossyScale.x,
                    node.transform.localPosition.y / transform.lossyScale.y,
                    node.transform.localPosition.z / transform.lossyScale.z
                    );
                node.transform.localScale = new Vector3(
                    nodeScale / transform.localScale.x,
                    nodeScale / transform.localScale.y/10,
                    nodeScale / transform.localScale.z
                    );
            }
    }

    private void OnDisable()
    {
        var count = transform.childCount;
        for (var i = count - 1; i >= 0; i--)
            DestroyImmediate(transform.GetChild(i).gameObject);
    }
}
